package com.snopy.leetcode.index1_1000.index301_400.spoffer;

import com.snopy.leetcode.TreeNode;
import com.snopy.utils.DataFactoryUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author snopy
 * @version 1.0.0
 * @classname Question55
 * @description 二叉树的深度
 *输入一棵二叉树的根节点，求该树的深度。从根节点到叶节点依次经过的节点（含根、叶节点）
 * 形成树的一条路径，最长路径的长度为树的深度。
 * 例如：
 * 给定二叉树 [3,9,20,null,null,15,7]，
 *     3
 *    / \
 *   9  20
 *     /  \
 *    15   7
 * 返回它的最大深度 3 。
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 * @email 77912204@qq.com
 * @date 2022/03/17 13:22
 */
@Slf4j
public class Question55_1 {

    public static void main(String[] args) {

        Integer[] trees = new Integer[]{3,9,20,null,null,15,7};
        TreeNode root = DataFactoryUtil.buildTree(trees);
        int maxDepth = maxDepth(root);
        log.info("maxDepth:{}",maxDepth);
        maxDepth = maxDepthIterate(root);
        log.info("maxDepth:{}",maxDepth);
    }
    /**
     * @Description 层级遍历
     * @param root:
     * @return: int
     * @Date 2022-03-17
     * @Author txl77912204@gmail.com
     **/
    public static int maxDepth(TreeNode root){
        Queue<TreeNode> queue = new LinkedList<>();
        if (root==null){
            return 0;
        }
        int depth = 0;
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left!=null){
                    queue.add(node.left);
                }
                if (node.right!=null){
                    queue.add(node.right);
                }
            }
            depth++;
        }
        return depth;
    }
    public static int maxDepthIterate(TreeNode root){
        if (root==null){
            return 0;
        }
        return 1+ Math.max(maxDepth(root.left),maxDepth(root.right));
    }
    public void left(TreeNode node,int depth){
        if (node==null){
            return;
        }
        depth+=1;
        left(node.left,depth);
    }
    public void right(TreeNode node,int depth){
        if (node==null){
            return;
        }
        depth+=1;
        right(node.right,depth);
    }
}
